import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public final class PropertyManager {
    private static Map<String, Object> xmlProperty = new ConcurrentHashMap<String, Object>();
    private static Map<String, Object> dbProperty = new ConcurrentHashMap<String, Object>();

    private PropertyManager() {

    }

    private static PropertyManager insstance = new PropertyManager();

    public static PropertyManager getInstance() {
        try {
            initXMLConfig();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return insstance;
    }

    public Set<String> getExcludeAuthUrls() {
        return (Set<String>) xmlProperty.get("parsedExcludeAuthUrls");

    }

    private static void initXMLConfig() throws Exception {
        SAXReader reader = new SAXReader(false);
        Document document = null;
        document = reader.read(Thread.currentThread().getContextClassLoader()
                .getResource("project-config.xml"));
        initExcludeAuthUrls(document
                .selectSingleNode("projectname/excludeAuthUrls"));
    }

    private static void initDbProperty() throws Exception {
        //从数据库里面读取属性
    }

    private static void initExcludeAuthUrls(Node excludeAuthUrlsNode) {
        Set<String> parsedExclude = new HashSet<String>();
        if (excludeAuthUrlsNode != null) {
            String excludeAuthUrls = excludeAuthUrlsNode.getText();
            excludeAuthUrls = excludeAuthUrls.replaceAll("\\s", "");
            String[] tmps = null;
            if (excludeAuthUrls.equals("")) {
                tmps = new String[0];
            } else {
                tmps = excludeAuthUrls.split(",");
            }
            for (String tmp : tmps) {
                tmp = tmp.replaceAll("\\.", "\\\\.");
                tmp = tmp.replaceAll("\\?", "\\\\?");
                tmp = tmp.replaceAll("\\$", "\\\\$");
                tmp = tmp.replaceAll("\\*", ".*");
                parsedExclude.add("^" + tmp + ".*");
            }
            xmlProperty.put("excludeAuthUrls", excludeAuthUrls);
            xmlProperty.put("parsedExcludeAuthUrls", parsedExclude);
        } else {
            xmlProperty.put("excludeAuthUrls", "");
            xmlProperty.put("parsedExcludeAuthUrls", parsedExclude);
        }
    }

    public static void main(String[] args) {
        for (String s : PropertyManager.getInstance().getExcludeAuthUrls()) {
            System.out.println(s);
        }
    }

}
